// cookie保存的天数
import config,{getWs} from '@/config'
import { forEach, hasOneOf, objEqual } from '@/libs/tools'
const { title, cookieExpires, useI18n } = config
import md5 from 'md5'
import _ from "lodash";

let wsurl = getWs()
export const TOKEN_KEY = 'token'

export const setToken = (token, data) => {
    localStorage.setItem(token, data);
}

export const getToken = (tokentitle) => {
    const token = localStorage.getItem(tokentitle);
    if (token) return token
    else return false
};


export const hasChild = (item) => {
    return item.children && item.children.length !== 0
}

const showThisMenuEle = (item, access) => {
    if (item.meta && item.meta.access && item.meta.access.length) {
        if (hasOneOf(item.meta.access, access)) return true
        else return false
    } else return true
}
/**
 * @param {Array} list 通过路由列表得到菜单列表
 * @returns {Array}
 */
export const getMenuByRouter = (list, access) => {
    let res = []
    forEach(list, item => {
        if (!item.meta || (item.meta && !item.meta.hideInMenu)) {
            let obj = {
                icon: (item.meta && item.meta.icon) || '',
                name: item.name,
                meta: item.meta
            }
            if ((hasChild(item) || (item.meta && item.meta.showAlways)) && showThisMenuEle(item, access)) {
                obj.children = getMenuByRouter(item.children, access)
            }
            if (item.meta && item.meta.href) obj.href = item.meta.href
            if (showThisMenuEle(item, access)) res.push(obj)
        }
    })
    return res
}

/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
export const getBreadCrumbList = (route, homeRoute) => {
    let homeItem = { ...homeRoute, icon: homeRoute.meta.icon }
    let routeMetched = route.matched
    if (routeMetched.some(item => item.name === homeRoute.name)) return [homeItem]
    let res = routeMetched.filter(item => {
        return item.meta === undefined || !item.meta.hideInBread
    }).map(item => {
        let meta = { ...item.meta }
        if (meta.title && typeof meta.title === 'function') {
            meta.__titleIsFunction__ = true
            meta.title = meta.title(route)
        }
        let obj = {
            icon: (item.meta && item.meta.icon) || '',
            name: item.name,
            meta: meta
        }
        return obj
    })
    res = res.filter(item => {
        return !item.meta.hideInMenu
    })
    return [{ ...homeItem, to: homeRoute.path }, ...res]
}

export const getRouteTitleHandled = (route) => {
    let router = { ...route }
    let meta = { ...route.meta }
    let title = ''
    if (meta.title) {
        if (typeof meta.title === 'function') {
            meta.__titleIsFunction__ = true
            title = meta.title(router)
        } else title = meta.title
    }
    meta.title = title
    router.meta = meta
    return router
}

export const showTitle = (item, vm) => {
    let { title, __titleIsFunction__ } = item.meta
    if (!title) return
    if (useI18n) {
        if (item.meta.title) title = vm.$t(item.meta.title)
        else if (title.includes('{{') && title.includes('}}') && useI18n) title = title.replace(/({{[\s\S]+?}})/, (m, str) => str.replace(/{{([\s\S]*)}}/, (m, _) => vm.$t(_.trim())))
        else if (__titleIsFunction__) title = item.meta.title
    } else title = (item.meta && item.meta.title) || item.name
    return title
}



/**
 * @param {*} list 现有标签导航列表
 * @param {*} newRoute 新添加的路由原信息对象
 * @description 如果该newRoute已经存在则不再添加
 */
export const getNewTagList = (list, newRoute) => {
    const { name, path, meta } = newRoute
    let newList = [...list]
    if (newList.findIndex(item => item.name === name) >= 0) return newList
    else newList.push({ name, path, meta })
    return newList
}



/**
 * @param {Object} file 从上传组件得到的文件对象
 * @returns {Promise} resolve参数是解析后的二维数组
 * @description 从Csv文件中解析出表格，解析成二维数组
 */
export const getArrayFromFile = (file) => {
    let nameSplit = file.name.split('.')
    let format = nameSplit[nameSplit.length - 1]
    return new Promise((resolve, reject) => {
        let reader = new FileReader()
        reader.readAsText(file) // 以文本格式读取
        let arr = []
        reader.onload = function (evt) {
            let data = evt.target.result // 读到的数据
            let pasteData = data.trim()
            arr = pasteData.split((/[\n\u0085\u2028\u2029]|\r\n?/g)).map(row => {
                return row.split('\t')
            }).map(item => {
                return item[0].split(',')
            })
            if (format === 'csv') resolve(arr)
            else reject(new Error('[Format Error]:你上传的不是Csv文件'))
        }
    })
}

/**
 * @param {Array} array 表格数据二维数组
 * @returns {Object} { columns, tableData }
 * @description 从二维数组中获取表头和表格数据，将第一行作为表头，用于在iView的表格中展示数据
 */
export const getTableDataFromArray = (array) => {
    let columns = []
    let tableData = []
    if (array.length > 1) {
        let titles = array.shift()
        columns = titles.map(item => {
            return {
                title: item,
                key: item
            }
        })
        tableData = array.map(item => {
            let res = {}
            item.forEach((col, i) => {
                res[titles[i]] = col
            })
            return res
        })
    }
    return {
        columns,
        tableData
    }
}

export const findNodeUpper = (ele, tag) => {
    if (ele.parentNode) {
        if (ele.parentNode.tagName === tag.toUpperCase()) {
            return ele.parentNode
        } else {
            return findNodeUpper(ele.parentNode, tag)
        }
    }
}

export const findNodeUpperByClasses = (ele, classes) => {
    let parentNode = ele.parentNode
    if (parentNode) {
        let classList = parentNode.classList
        if (classList && classes.every(className => classList.contains(className))) {
            return parentNode
        } else {
            return findNodeUpperByClasses(parentNode, classes)
        }
    }
}

export const findNodeDownward = (ele, tag) => {
    const tagName = tag.toUpperCase()
    if (ele.childNodes.length) {
        let i = -1
        let len = ele.childNodes.length
        while (++i < len) {
            let child = ele.childNodes[i]
            if (child.tagName === tagName) return child
            else return findNodeDownward(child, tag)
        }
    }
}

export const showByAccess = (access, canViewAccess) => {
    return hasOneOf(canViewAccess, access)
}

/**
 * @description 根据name/params/query判断两个路由对象是否相等
 * @param {*} route1 路由对象
 * @param {*} route2 路由对象
 */
export const routeEqual = (route1, route2) => {
    const params1 = route1.params || {}
    const params2 = route2.params || {}
    const query1 = route1.query || {}
    const query2 = route2.query || {}
    return (route1.name === route2.name) && objEqual(params1, params2) && objEqual(query1, query2)
}

/**
 * 判断打开的标签列表里是否已存在这个新添加的路由对象
 */
export const routeHasExist = (tagNavList, routeItem) => {
    let len = tagNavList.length
    let res = false
    doCustomTimes(len, (index) => {
        if (routeEqual(tagNavList[index], routeItem)) res = true
    })
    return res
}

export const localSave = (key, value) => {
    localStorage.setItem(key, value)
}

export const localRead = (key) => {
    return localStorage.getItem(key) || ''
}

// scrollTop animation
export const scrollTop = (el, from = 0, to, duration = 500, endCallback) => {
    if (!window.requestAnimationFrame) {
        window.requestAnimationFrame = (
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function (callback) {
                return window.setTimeout(callback, 1000 / 60)
            }
        )
    }
    const difference = Math.abs(from - to)
    const step = Math.ceil(difference / duration * 50)

    const scroll = (start, end, step) => {
        if (start === end) {
            endCallback && endCallback()
            return
        }

        let d = (start + step > end) ? end : start + step
        if (start > end) {
            d = (start - step < end) ? end : start - step
        }

        if (el === window) {
            window.scrollTo(d, d)
        } else {
            el.scrollTop = d
        }
        window.requestAnimationFrame(() => scroll(d, end, step))
    }
    scroll(from, to, step)
}

/**
 * @description 根据当前跳转的路由设置显示在浏览器标签的title
 * @param {Object} routeItem 路由对象
 * @param {Object} vm Vue实例
 */
export const setTitle = (routeItem, vm) => {
    const handledRoute = getRouteTitleHandled(routeItem)
    const pageTitle = showTitle(handledRoute, vm)
    const resTitle = pageTitle ? `${title} - ${pageTitle}` : title
    window.document.title = resTitle
}


/**
 * 判断手机号还是邮箱
 */
export const EmailSms = (data) => {
    // return data.indexOf("@") != -1;
    return /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(data)
}

/**
 * 手机号邮箱中间四位变星号
 */
export const Hidephone = (data) => {
    var $rs;
    if (EmailSms(data)) {
        let splitdata = data.indexOf("@");
        $rs = data.substr(0, splitdata / 2) + "****" + data.substring(splitdata, data.length);
    } else {
        $rs = data.substr(0, 3) + "****" + data.substring(7, 11);
    }
    return $rs;
}


/**
 * 密码加密
 */
export const Passwordencryption = (data) => {
    let _Data = _.cloneDeep(data)
    /**
     * 重复加密
     * @param {string} str 需加密的字符串
     * @param num 加密次数
     */
    let md5Call = (str,num=5)=>{
        for (let index = 0; index < num; index++) {
            str=md5(str)
        }
        return str
    }
    try {
        _Data.password = md5Call(_Data.password);
    } catch (err) {
    };
    try {
        _Data.old_password = md5Call(_Data.old_password);
    } catch (err) {
    };
    try {
        _Data.password_confirmation = md5Call(_Data.password_confirmation);
    } catch (err) {
    };
    try {
        _Data.payment_password = md5Call(_Data.payment_password);
    } catch (err) {
    };
    try {
        _Data.old_login_pwd = md5Call(_Data.old_login_pwd);
    } catch (err) {
    };
    try {
        _Data.new_login_pwd = md5Call(_Data.new_login_pwd);
    } catch (err) {
    };
    try {
        _Data.new_login_pwd_confirmation = md5Call(_Data.new_login_pwd_confirmation);
    } catch (err) {
    };
    try {
        _Data.new_pay_pwd = md5Call(_Data.new_pay_pwd);
    } catch (err) {
    };
    try {
        _Data.new_pay_pwd_confirmation = md5Call(_Data.new_pay_pwd_confirmation);
    } catch (err) {
    };
    return _Data;
}


export const codelist = (data) => {
    
    let codeList = data.map(item => item.code).join("|");

    setToken("codeList", codeList);

};

var windowWebSocket, timersy;

export const contractws = (data, domthis) => {  //行情数据
    if (domthis == "unsub") {
        if(windowWebSocket.readyState==1){
            clearInterval(timersy);
            windowWebSocket.send(JSON.stringify(data));
            windowWebSocket.close();
        }
        return false;
    };
    // 首先判断是否 支持 WebSocket
    if ('WebSocket' in window) {
        windowWebSocket = new WebSocket(wsurl);
    } else if ('MozWebSocket' in window) {
        windowWebSocket = new MozWebSocket(wsurl);
    } else {
        windowWebSocket = new SockJS(wsurl);
    }
    // 打开时
    windowWebSocket.onopen = function (evnt) {
        // 发送消息
        windowWebSocket.send(JSON.stringify(data));
        timersy = setInterval(() => {
            windowWebSocket.send(JSON.stringify('123')); // 发送消息
        }, 5000)
    };
    // 处理消息时
    windowWebSocket.onmessage = function (evnt) {
         
        if (evnt.data.split('{').length != "2") {
            return false;
        };
        let datanum = JSON.parse(evnt.data);
        datanum.cnyPrice = _.round(datanum.cnyPrice, 4);
        datanum.price = _.round(datanum.price, 4);
        domthis.contractwslist(datanum);
    };
    windowWebSocket.onerror = function (evnt) {
        console.log("  websocket.onerror");
    };
    windowWebSocket.onclose = function (evnt) {
        console.log("  websocket.onclose");
    };
};


var windowWebSocketdepth, timersydepth;

export const contractwsdepth = (data, domthis) => { //盘口数据
    if (domthis == "unsub") {
        if(windowWebSocketdepth.readyState==1){
            clearInterval(timersydepth);
            windowWebSocketdepth.send(JSON.stringify(data));
            windowWebSocketdepth.close();
        }
        return false;
    };
    // 首先判断是否 支持 WebSocket
    if ('WebSocket' in window) {
        windowWebSocketdepth = new WebSocket(wsurl);
    } else if ('MozWebSocket' in window) {
        windowWebSocketdepth = new MozWebSocket(wsurl);
    } else {
        windowWebSocketdepth = new SockJS(wsurl);
    }
    // 打开时
    windowWebSocketdepth.onopen = function (evnt) {
        // 发送消息
        windowWebSocketdepth.send(JSON.stringify(data));
        timersydepth = setInterval(() => {
            windowWebSocketdepth.send(JSON.stringify('123')); // 发送消息
        }, 5000)
    };
    // 处理消息时
    windowWebSocketdepth.onmessage = function (evnt) {
        let datanum = JSON.parse(evnt.data);
        let bidsdata = 0, asksdata = 0;
        datanum.asks = _.reverse(datanum.asks);

        datanum.asks.map(function (item, index, ary) {
            asksdata = _.add(asksdata, _.round(item.totalSize, 3));
            item.cumulative = _.round(asksdata, 3);
            item.price = _.round(item.price, 3);
        });
        datanum.bids.map(function (item, index, ary) {
            bidsdata = _.add(bidsdata, _.round(item.totalSize, 3));
            item.cumulative = _.round(bidsdata, 3);
            item.price = _.round(item.price, 3);
        });
        // datanum.bids = _.reverse(datanum.bids);

        domthis.contractwsdepthlist(datanum);
    };
    windowWebSocketdepth.onerror = function (evnt) {
        console.log("  websocket.onerror");
    };
    windowWebSocketdepth.onclose = function (evnt) {
        console.log("  websocket.onclose");
    };
};


var windowWebSockettrader, timersytrader;

export const contractwstrader = (data, domthis) => { //盘口数据
    if (domthis == "unsub") {
        if(windowWebSockettrader.readyState==1){
            clearInterval(timersytrader);
            windowWebSockettrader.send(JSON.stringify(data));
            windowWebSockettrader.close();
        }
        return false;
    };
    // 首先判断是否 支持 WebSocket
    if ('WebSocket' in window) {
        windowWebSockettrader = new WebSocket(wsurl);
    } else if ('MozWebSocket' in window) {
        windowWebSockettrader = new MozWebSocket(wsurl);
    } else {
        windowWebSockettrader = new SockJS(wsurl);
    }
    // 打开时
    windowWebSockettrader.onopen = function (evnt) {
        // debugger
        // 发送消息
        windowWebSockettrader.send(JSON.stringify(data));
        timersytrader = setInterval(() => {
            windowWebSockettrader.send(JSON.stringify('123')); // 发送消息
        }, 5000)
    };
    // 处理消息时
    windowWebSockettrader.onmessage = function (evnt) {
        let datanum = JSON.parse(evnt.data);
        let i = 0, len1;
        for (len1 = datanum.length; i < len1; i++) {
            datanum[i].price = _.reverse(datanum[i].price, 2);
        };
        domthis.contractwstraderlist(datanum);
    };
    windowWebSockettrader.onerror = function (evnt) {
        console.log("  websocket.onerror");
    };
    windowWebSockettrader.onclose = function (evnt) {
        console.log("  websocket.onclose");
    };
};

/*
    balance: 可以余额
    from: 上传
    codetype: 单币种数据
*/
export const CalculationTotal = (balance, from, codetype) => {//总张数
    let zhong = _.round(_.divide(balance, CalculationPrice(from, codetype)), 4);
    return zhong;
}

/*
    from: 上传
    codetype: 单币种数据
*/
export const CalculationPrice = (from, codetype) => {//单张价格
    let Prodata = _.cloneDeep(from);
    // let leverage = _.add(_.divide(1, _.toFinite(Prodata.leverage)), _.toFinite(codetype.handling_fee));
    let leverage = Prodata.leverage;
    let dangejiage = _.round(_.divide(_.multiply(Prodata.buy_price, codetype.sheet_num), leverage), 4);
    return dangejiage;
}

export const multiplys = (num, price) => {//单张价格
    let zongjia = _.multiply(num, price);
    return zongjia
}

